<template>
  <div id="sddDepart">
    <table>
      <tr>
        <td><span style="color: red">*</span>部门编号</td>
        <td><el-input v-model="depart.code"></el-input></td>
      </tr>
      <br />
      <tr>
        <td><span style="color: red">*</span>部门名称</td>
        <td><el-input v-model="depart.relationName"></el-input></td>
      </tr>
      <br />
      <tr>
        <td>上级部门</td>
        <td>
          <span v-if="selectedNode">{{ selectedNode.relationName }}</span
          ><span v-else>没有上级部门</span>
        </td>
        <td>
          <el-popover placement="right" width="400" v-model="visible">
            <el-tree
              :data="treeDate"
              :props="defaultProps"
              show-checkbox
              node-key="relationId"
              :check-strictly="true"
              @check="handleCheck"
              ref="tree"
            />
            <el-button slot="reference">点击选择上级部门</el-button>
          </el-popover>
        </td>
      </tr>
      <br />
    </table>
  </div>
</template>

<script>
export default {
  name: "AddDepart",
  data() {
    return {
      defaultProps: {
        children: "children",
        label: "relationName",
      },
      selectedNode: null,
      visible: false,
      cid: 1,
      departs: [],
      treeDate: [],
      isVaCode: false,
      isVaName: false,
      ralation: [],
      depart: {
        relationName: "",
        code: "",
        relationId: "",
      },
    };
  },
  methods: {
    letNull() {
      this.selectedNode = null;
      this.depart.relationName = "";
      this.depart.code = "";
      this.depart.relationId = "";
      this.ralation = [];
      this.$refs.tree.setCheckedKeys([]);
    },
    addAndUp: async function () {
      const relationName = this.depart.relationName;
      const code = this.depart.code;
      let parentId = null;
      const relationId = this.depart.relationId;

      if (this.selectedNode) {
        parentId = this.selectedNode.relationId;
      }

      if (!code) {
        this.$message({
          showClose: true,
          message: "部门编码不可以为空",
          type: "error",
        });
        return false;
      }

      await this.vaCode();

      if (relationId && code == this.ralation.code) {
      } else if (this.isVaCode) {
        this.$message({
          showClose: true,
          message: "部门编码重复",
          type: "error",
        });
        return false;
      }

      if (!relationName) {
        this.$message({
          showClose: true,
          message: "部门名称不可以为空",
          type: "error",
        });
        return false;
      }

      await this.vaName();

      if (relationId && relationName == this.ralation.relationName) {
      } else if (this.isVaName) {
        this.$message({
          showClose: true,
          message: "部门名称重复",
          type: "error",
        });
        return false;
      }

      if (!relationId) {
        try {
          const rs = await this.axios({
            url: "/info/relation/add",
            method: "POST",
            data: {
              code,
              relationName,
              parentId,
            },
          });
          if (rs.data.code === 200) {
            this.$message({
              showClose: true,
              message: "添加成功",
              type: "success",
            });

            this.letNull();
            return true;
          } else {
            this.$message({
              showClose: true,
              message: "添加失败",
              type: "error",
            });

            return false;
          }
        } catch (error) {
          this.$message({
            showClose: true,
            message: "添加失败,请求失败",
            type: "error",
          });
          return false;
        }
      } else {
        try {
          const rs = await this.axios({
            url: "/info/relation/up",
            method: "POST",
            data: {
              relationId,
              code,
              relationName,
              parentId,
            },
          });

          if (rs.data.code === 200) {
            this.$message({
              showClose: true,
              message: "修改成功",
              type: "success",
            });
            this.letNull();

            return true;
          } else {
            this.$message({
              showClose: true,
              message: "修改失败",
              type: "error",
            });

            return false;
          }
        } catch (error) {
          console.error("请求失败:", error);
          return false;
        }
      }
    },
    selectById(id) {
      this.axios({
        url: "/info/relation/selectById",
        params: {
          relationId: id,
        },
      }).then((rs) => {
        this.ralation = rs.data.relation;
        this.depart.relationName = rs.data.relation.relationName;
        this.depart.code = rs.data.relation.code;
        this.depart.relationId = rs.data.relation.relationId;
        this.$refs.tree.setCheckedKeys([rs.data.relation.parentId]);

        const checkedNodes = this.$refs.tree.getCheckedNodes();
        if (checkedNodes.length > 0) {
          const selectedNode = checkedNodes[0];
          this.selectedNode= {
            relationId: selectedNode.relationId,
            relationName: selectedNode.relationName,
          };
        }
      });
    },
    vaCode: async function () {
      await this.axios({
        url: "/info/relation/selectCount",
        params: {
          code: this.depart.code,
        },
      }).then((rs) => {
        if (rs.data.count > 0) {
          this.isVaCode = true;
        } else {
          this.isVaCode = false;
        }
      });
    },
    vaName: async function () {
      await this.axios({
        url: "/info/relation/selectCount",
        params: {
          relationName: this.depart.relationName,
          parentId: this.depart.parentId,
        },
      }).then((rs) => {
        if (rs.data.count > 0) {
          this.isVaName = true;
        } else {
          this.isVaName = false;
        }
      });
    },
    handleCheck(node, checked, indeterminate) {
      // 如果有其他节点被选中，则取消选中
      console.log(node);
      if (checked) {
        if (
          this.selectedNode &&
          this.selectedNode.relationId !== node.relationId
        ) {
          const previouslySelectedNode = this.$refs.tree.getNode(
            this.selectedNode.relationId
          );
          this.$refs.tree.setChecked(previouslySelectedNode, false);
        }
        this.selectedNode = {
          relationId: node.relationId,
          relationName: node.relationName,
        };
      } else {
        if (
          this.selectedNode &&
          this.selectedNode.relationId === node.relationId
        ) {
          this.selectedNode = null;
        }
      }
      this.visible = false;
    },
    selectRe() {
      this.axios({
        url: "/info/relation/selectRe",
        params: {
          statu: 1,
          cid: this.cid,
        },
      }).then((rs) => {
        console.log(rs);
        this.departs = rs.data.ralation;
        this.treeDate = this.buildTree(this.departs);
      });
    },
    buildTree(data) {
      const tree = [];
      const map = {};
      let com = this.cid;

      // 将所有节点添加到map中，方便后续查找
      data.forEach((item) => {
        map[item.relationId] = { ...item, children: [] };
      });

      // 构建树形结构
      data.forEach((item) => {
        console.log("Before building tree:", item);
        if (item.parentId === com) {
          // 如果父ID匹配，直接添加到树数组中
          tree.push(map[item.relationId]);
        } else {
          // 否则，找到父节点并添加到父节点的子节点数组中
          if (map[item.parentId]) {
            map[item.parentId].children.push(map[item.relationId]);
          }
        }
        console.log("After building tree:", tree);
        console.log(tree[0].statu);
      });

      return tree;
    },
  },
  created() {
    this.selectRe();
  },
};
</script>

<style scoped>
#addDepart {
  width: 100%;
  height: 200px;
  /* overflow: scroll; */
  /* background-color: pink; */
}

#contact {
  width: 90%;
  margin: auto;
  border-collapse: collapse;
  color: #707276;
}

#contact th,
#contact td {
  border: 1px #c0c4cc solid;
  height: 35px;
  min-width: 30px;
}

p {
  color: #4b4a4a;
  font-size: 18px;
}

.el-input {
  width: 240px;
}

table td :not([id="contact"]) {
  text-align: left;
  padding-right: 10px;
  /* padding-top: 10px;
  padding-bottom: 10px; */
}

td:nth-child(odd) {
  text-align: center;
  padding-right: 10px;
}
</style>